<template>
    <el-card shadow="never">
        <div class="title_box">
            <div>收集表明细</div>
        </div>
        <el-divider />
        <el-radio-group v-model="pageType" class="changeRadio" @change="onBtnChange">
            <el-radio-button :label="1">访客记录</el-radio-button>
            <el-radio-button :label="2">填写明细</el-radio-button>
        </el-radio-group>
        <ZwSearchForm
            ref="searchFormRef"
            row-num="3"
            :option="searchOption"
            @search="search"
            @reset="reset"
            @expand="getTableH" />
        <div class="table-export">
            <el-button :disabled="!tableData.length" @click="onExportExcel">导出</el-button>
        </div>
        <ZwTable
            v-if="tableVisible"
            ref="tableRef"
            is-limit-height
            class="table-box"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApiVal"
            @updateData="getTableList"></ZwTable>
    </el-card>
    <!-- <BatchLabel ref="BatchLabelRef" @save="getTagsFun" /> -->
    <!-- 收集表弹窗 -->
    <!-- <CollectPopup ref="CollectPopupRef" :CollectPopupData="CollectPopupData" /> -->
    <el-drawer v-model="visible" :title="`查看收集表-${title}`" size="40%">
        <StatPreviewForm
            ref="StatPreviewFormRef"
            :control-card-columns="controlCardColumns"
            :cover-image="coverImage"
            :read-only="true" />
        <template #footer>
            <el-button type="primary" @click="onExport">导出</el-button>
        </template>
    </el-drawer>
    <!-- 浏览详情 -->
    <VisitorInfo v-model="visitor" :options="visitorOptions" />
    <!-- 标签 -->
    <ZwBatchLabel ref="BatchLabelRef" @save="getTagsFun"></ZwBatchLabel>
</template>

<script setup lang="tsx">
import { ref, inject, nextTick, watch, withDefaults, defineProps, defineEmits, reactive, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import {
    statdetailList,
    viewcollectList,
    statexportList,
    collectDetailCols,
    collectSubmitDetail,
    collectStatDetailExport,
    collectSubmitDetailExport
} from '@/api/highMaterial/collectionTable';
import { useStore } from '@/store';
import { deepCopy } from '@/utils/helper';
import { DOWLOAD_FILE } from '@/utils/smartMarketing';
import { ElTooltip, ElImage, ElIcon, ElPopover, ElTag, ElButton } from 'element-plus';

import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';

import StatPreviewForm from '../../components/StatPreviewForm/index.vue';
// import BatchLabel from '@/components/BatchLabel.vue';
import CollectPopup from './CollectPopup.vue';
import VisitorInfo from './VisitorInfo.vue';
import html2canvas from 'html2canvas';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import { QuestionFilled } from '@element-plus/icons-vue';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';

interface Props {
    paramselist: any;
}

const router = useRouter();
const route = useRoute();
const store = useStore();
const props = withDefaults(defineProps<Props>(), {
    paramselist: () => {
        return {
            data: []
        };
    }
});
const emit = defineEmits(['submitdetailed']);
const PaginationRef = ref<any>(null);
const CollectPopupRef = ref<any>(null);
const tableRef = ref<any>(null);
const searchFormRef = ref<any>(null);
const CollectPopupData = ref([]);
const pageType = ref(1);
const tableData = reactive([]);
const formData: any = ref({
    type: pageType.value,
    select_tag_type: -1
});
const visitor = ref<boolean>(false);
const visitorOptions = ref<any>({});

const searchOption = computed(() => {
    const list = [
        {
            label: '访客信息',
            name: 'name',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '请输入访客名称'
        },
        {
            label: '客户标签',
            name: 'tag',
            value: [],
            type: 'select',
            tagTypeName: 'select_tag_type',
            multiple: true,
            isBatchLabel: true,
            isAtom: true,
            popperClass: 'zw-hide_select_option'
        },
        {
            label: '提交时间',
            name: 'time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        }
    ];
    if (pageType.value == 1) {
        return [list[0]];
    } else {
        return [list[0], list[2]];
    }
});

const tableVisible = ref(true);
const tableOption = computed(() => {
    const arr = [
        {
            label: '访客信息',
            minWidth: 200,
            fixed: 'left',
            render({ row, column, index }) {
                const slotError = () => (
                    <div class="image_slot">
                        <ElIcon>
                            <IconPicture />
                        </ElIcon>
                    </div>
                );
                return (
                    <div class="cusInfo cus-info">
                        <ElImage
                            vSlots={{ error: slotError }}
                            src={
                                (pageType.value == 1 ? row.headimgurl : row?.visitor_name?.headimgurl) ||
                                'https://img-scrm-dev.keyid.cn/keyid-scrm-server/avatar/cust_default.png'
                            }
                            fit="cover"
                            class="avatar"></ElImage>
                        <ElTooltip
                            effect="dark"
                            content={(pageType.value == 1 ? row.nickname : row?.visitor_name?.nickname) || '未知客户'}
                            placement="top-start">
                            <div class="name">
                                {(pageType.value == 1 ? row.nickname : row?.visitor_name?.nickname) || '未知客户'}
                            </div>
                        </ElTooltip>
                    </div>
                );
            }
        },
        {
            prop: 'first_visit_time',
            label: '首次访问时间',
            minWidth: 200
        },
        {
            prop: 'visit_num',
            label: '访问次数',
            minWidth: 200
        },
        {
            prop: 'submit_time',
            label: '提交时间',
            minWidth: 200
        },
        // {
        //     prop: 'tag_list',
        //     label: (
        //         <div class="box-item-div">
        //             <span>添加标签</span>
        //             <el-tooltip
        //                 class="box-item"
        //                 effect="dark"
        //                 content="添加标签展示用户通过当前收集表添加的标签"
        //                 placement="top">
        //                 <el-icon class="box-icon">
        //                     <QuestionFilled />
        //                 </el-icon>
        //             </el-tooltip>
        //         </div>
        //     ),
        //     isTag: true,
        //     minWidth: 200
        // },
        {
            prop: 'operate',
            label: '操作',
            fixed: 'right',
            width: 150,
            isOperate: true,
            renderOperate({ row, column, index }) {
                const rowType = pageType.value == 1 ? row?.type : row?.visitor_name?.type;
                const rowId = pageType.value == 1 ? row?.cust_id : row?.visitor_name?.cust_id;
                return (
                    <div>
                        {pageType.value == 1 && (
                            <ElTooltip
                                effect="dark"
                                disabled={row.wx_openid}
                                content="当前客户尚未授权，无法查看访问记录。"
                                placement="top">
                                <ElButton
                                    type="text"
                                    class={{ 'custom-text-btn': true, disabled: !row.wx_openid }}
                                    plain
                                    onClick={() => row.wx_openid && toVisitorDetail(row)}>
                                    访问记录
                                </ElButton>
                            </ElTooltip>
                        )}
                        {/* <ElButton
                            class="custom-text-btn"
                            size="small"
                            type="text"
                            plain
                            vShow={pageType.value == 2}
                            onClick={() => toDetail(row)}>
                            查看收集表
                        </ElButton> */}
                        <ElTooltip
                            effect="dark"
                            disabled={rowId != 0}
                            content="当前客户非企业客户，不支持查看客户详情。"
                            placement="top">
                            <ElButton
                                type="text"
                                class={{ 'custom-text-btn': true, disabled: rowId == 0 }}
                                plain
                                onClick={() =>
                                    rowId != 0 &&
                                    router.push({
                                        path: '/customer/manage/list/detail',
                                        query: { id: rowId, type: rowType }
                                    })
                                }>
                                客户详情
                            </ElButton>
                        </ElTooltip>
                    </div>
                );
            }
        }
    ];
    if (pageType.value == 1) {
        return [arr[0], arr[1], arr[2], arr[4]];
    } else {
        const dynamicColList = dynamicCols.map(item => {
            // todo: 图片
            if (['carousel', 'picture'].includes(item.type)) {
                const slotError = () => (
                    <div class="picture_slot">
                        <ElIcon>
                            <IconPicture />
                        </ElIcon>
                    </div>
                );
                return {
                    prop: item.code,
                    label: item.name,
                    minWidth: 200,
                    render({ row, column, index }) {
                        return (
                            <div class="cusInfo">
                                {row[item.code] ? (
                                    <ElImage
                                        vSlots={{ error: slotError }}
                                        src={row[item.code] + '!zwlazy'}
                                        fit="cover"
                                        class="custom-picture"
                                        z-index={9999}
                                        loading="lazy"
                                        preview-teleported={true}
                                        preview-src-list={[row[item.code]]}></ElImage>
                                ) : (
                                    '--'
                                )}
                            </div>
                        );
                    }
                };
            } else {
                return {
                    prop: item.code,
                    label: item.name,
                    minWidth: 200,
                    render({ row, column, index }) {
                        return (
                            <ElTooltip
                                popper-class="custom-key-popover-tip"
                                effect="dark"
                                disabled={!row[item.code]}
                                content={row[item.code]}
                                placement="top">
                                <div class="custom-inline">{row[item.code] || '--'}</div>;
                            </ElTooltip>
                        );
                    }
                };
            }
        });
        return [arr[0], arr[3], ...dynamicColList, arr[4]];
    }
    // return arr;
});
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
// const fetchApi = () => {
//     // 获取文件列表
//     // getTableH()
//     return statdetailList;
// };
const fetchApiVal = ref(statdetailList);
const getRowKey = (row: any) => {
    return row.id;
};
const defaultParams = computed(() => {
    if (pageType.value == 1) {
        return {
            type: pageType.value,
            name: '',
            tag: [],
            select_tag_type: formData.value.select_tag_type
        };
    } else {
        return {
            name: '',
            time: []
        };
    }
});
const state = reactive({
    searchParams: deepCopy({ ...defaultParams.value, ...props.paramselist })
});
const search = (data: any) => {
    let select_tag_type = null;
    if (pageType.value == 1) {
        select_tag_type = !data?.tag || !data?.tag?.length ? -1 : data.select_tag_type;
    }
    state.searchParams = deepCopy({
        ...defaultParams.value,
        ...data,
        select_tag_type,
        id: props?.paramselist?.id,
        type: pageType.value
    });
    getDetailCols();
};
const reset = () => {
    state.searchParams = deepCopy({ ...defaultParams.value, id: props?.paramselist?.id, type: pageType.value });
    getDetailCols();
};
const changeParams = (v: any) => {
    state.searchParams = deepCopy({ ...defaultParams.value, ...props.paramselist });
};

const dynamicCols = reactive([]);
const getTableCol = async () => {
    const res = await collectDetailCols({ id: route.query.id });
    dynamicCols.length = 0;
    dynamicCols.push(...(res || []));
};

const getDetailCols = () => {
    tableVisible.value = false;
    if (pageType.value == 2) {
        getTableCol();
    }
    nextTick(() => {
        tableVisible.value = true;
    });
};

const onBtnChange = (v: any) => {
    formData.value.type = v;
    if (v == 1) {
        fetchApiVal.value = statdetailList;
    } else {
        fetchApiVal.value = collectSubmitDetail;
    }
    state.searchParams.type = v;
    searchFormRef.value.reset();
};
const getTagType = (val: number) => {
    switch (val) {
        case 0:
            return 3;
        case 1:
            return 1;
        case 2:
            return 2;
    }
};
const tabsList = ref<any>([]);
const BatchLabelRef = ref<any>(null);
// const openBatchLabel = () => {
//     BatchLabelRef.value.dialogData.delname = '不移除';
//     BatchLabelRef.value.title = '选择客户标签';
//     BatchLabelRef.value.dialogData.labelChooseType = 2;
//     BatchLabelRef.value.chooseDataArr = [];
//     if (tabsList.value.length > 0) {
//         BatchLabelRef.value.chooseDataArr = tabsList.value;
//     }
//     BatchLabelRef.value.dialogVisible = true;
// };
let BATCH_TYPE = 'enter';
// 打开选择标签弹框
const openBatchLabel = (type: string) => {
    BATCH_TYPE = type;
    BatchLabelRef.value.dialogVisible = true;
    BatchLabelRef.value.title = '批量打标签';
    BatchLabelRef.value.hasConditiion = false;
    BatchLabelRef.value.chooseDataArr.splice(
        0,
        BatchLabelRef.value.chooseDataArr.length,
        ...formData[`tags_${BATCH_TYPE}`]
    );
    // BatchLabelRef.value.chooseDataArr = [...formData[`tags_${BATCH_TYPE}`]];
};
// 获取当前选中的标签
const getTagsFun = async (val?: any) => {
    formData.value.tag = val?.idList;
    //  0: 无标签，1：满足任意一个标签， 2：同时满足所有标签
    // formData.value.select_tag_type = getTagType(val.labelType)
    formData.value.select_tag_type = val.labelType;
    tabsList.value = val.data;
};
//切换标签
const changeLabel = (value: any, al: any) => {
    tabsList.value = tabsList.value.filter((item: any) => {
        return value.includes(item.id);
    });
};
// 统计详细数据
const StatPreviewFormRef = ref<any>();
const visible = ref<boolean>(false);
const coverImage = ref<string>('');
const controlCardColumns = reactive<Array<any>>([]);
const title = ref<string>('');
const toDetail = async (v: any) => {
    viewcollectList({ id: props.paramselist.id, record_id: v.id }).then((res: any) => {
        visible.value = true;
        title.value = res.name;
        coverImage.value = res.cover_image;
        const map = new Map();
        for (const iterator of res.form_data || []) {
            map.set(iterator.key, iterator);
        }
        controlCardColumns.splice(
            0,
            controlCardColumns.length,
            ...res.config.map((v: any, i: number) => {
                return { ...v, ...(map.get(v.key) || {}) };
            })
        );
        nextTick(() => StatPreviewFormRef.value.setState());
    });
};

const getTableList = res => {
    tableData.length = 0;
    tableData.push(...(res || []));
};

const onExport = (options = {}) => {
    const container: any = document.querySelector('.preview-card-form.previre-form');
    // 设置放大倍数
    const scale = 1;

    // 传入节点原始宽高
    const _width = container.offsetWidth * 2;
    const _height = container.offsetHeight * 2;
    // html2canvas配置项
    const ops = {
        scale,
        _width,
        _height,
        useCORS: true,
        allowTaint: false,
        ...options
    };
    return html2canvas(container, ops).then(canvas => {
        // 返回图片的二进制数据
        const pageData = canvas.toDataURL('image/png', 1.0);
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = pageData;
        link.setAttribute('download', '收集表' + '.png');
        document.body.appendChild(link);
        link.click();
    });
};
const onExportExcel = e => {
    const params = {
        ...state.searchParams
    };
    // if (pageType.value == 1) {
    //     params = {
    //         ...props.paramselist,
    //         ...defaultParams.value
    //     };
    // } else {
    //     params = {
    //         ...props.paramselist,
    //         ...defaultParams.value
    //     };
    // }
    const api = pageType.value == 1 ? statexportList : collectSubmitDetailExport;
    api(params).then((res: any) => {
        // tableData.value = res.data
        // DOWLOAD_FILE(res.url, res.name);
        // todo:异步任务
        parabolaAnimation(e);
        ShowTaskMessage(`${pageType.value == 1 ? '访客记录' : '填写明细'}导出异步任务创建成功`);
    });
};

const toVisitorDetail = (val: any) => {
    visitorOptions.value = {
        id: props.paramselist.id,
        wx_openid: val.wx_openid
    };
    visitor.value = true;
};
defineExpose({
    changeParams
});
</script>

<style lang="scss">
.custom-key-popover-tip {
    max-width: 240px;
    word-wrap: break-word;
    white-space: pre-wrap;
    word-break: break-all;
}
</style>
<style lang="scss" scoped>
:deep.el-tag.el-tag--warning {
    margin-right: 10px;
}

:deep.el-card {
    margin-top: 20px;
}

.title_box {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* .el-divider {
    margin-top: 8px;
    margin-bottom: 16px;
} */

#echarts {
    display: flex;
    justify-content: center;
    height: 320px;
}

.empty_img {
    transform: translateX(13%);
}

.customer_list_search {
    padding: 16px;
    margin: 20px 0;
    background-color: #f9f9f9;

    .item_box {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        grid-gap: 20px;

        .el-form-item {
            :deep(.el-input__inner) {
                width: 100%;
            }

            margin: 0;

            .el-select {
                width: 100%;
            }

            .btn_box {
                text-align: right;
            }
        }
    }
}

.table-box {
    .avatar-box {
        display: flex;
        justify-content: flex-start;
        align-items: center;

        // .avatar {
        //   width: 50px;
        //   height: 50px;
        //   border-radius: 4px;
        // }

        .image-slot {
            .el-icon {
                font-size: 50px;
            }
        }

        .name {
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            font-weight: 300;
            color: #33302d;
            max-width: 90px;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
            word-break: break-all;
            margin: 0 10px;
        }

        .sex {
            width: 18px;
            height: 18px;
        }
    }

    .crop {
        display: flex;
        align-items: center;

        .crop_awatar {
            width: 50px;
            height: 50px;
            margin-right: 10px;
        }

        .crop_info {
            .crop_name {
                width: 130px;
                height: 23px;
                font-size: 14px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            .crop_contact {
                font-size: 12px;
                color: #969696;

                .crop_contact_look {
                    color: #ff6b00;
                    cursor: pointer;
                }
            }
        }
    }

    .tabs-list {
    }

    .btn-box {
        text-align: left;

        div {
            cursor: pointer;
            display: inline-block;
            vertical-align: middle;

            // width: 80px;
            height: 32px;
            background: #fff;
            border: 1px solid #eaeaea;
            text-align: center;
            line-height: 32px;
            margin: 0 6px 5px;
            min-height: 28px;
            padding: 0 15px;
            font-size: 12px;
            border-radius: calc(var(--el-border-radius-base) - 1px);
        }
    }

    :deep(.custom-text-btn) {
        margin: 0 !important;
        padding: 0 !important;
        min-width: auto !important;

        & + .custom-text-btn {
            margin-left: 16px !important;
            position: relative;

            &::before {
                content: '';
                position: absolute;
                height: 45%;
                width: 1px;
                background-color: rgb(220 223 230);
                top: 50%;
                left: -9px;
                transform: translateY(-50%);
            }
        }

        &.disabled {
            cursor: not-allowed;
            color: rgb(255 107 0 / 50%);
        }
    }

    :deep(.box-item-div) {
        display: flex;
        line-height: 1;
    }

    :deep(.custom-picture) {
        width: 36px;
        height: 36px;
    }

    :deep(.picture_slot) {
        width: 36px;
        height: 36px;

        i {
            font-size: 36px;
        }
    }

    :deep(.custom-inline) {
        display: inline-block;
        max-width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        margin-bottom: -7px;
    }
}

.changeRadio {
    margin-bottom: 16px;
}

:deep(.cusInfo) {
    display: flex;
    align-items: center;

    .avatar {
        width: 36px;
        height: 36px;
        min-width: 36px;
        border-radius: 4px;
    }

    .name {
        margin: 0 10px;
    }
}

:deep(.cus-info) {
    .image_slot {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;

        i {
            font-size: 30px;
        }
    }
}

:deep(.defaultTags) {
    margin: 0 10px;
}

.table-export {
    display: flex;
    justify-content: flex-end;
}
</style>
